var app = getApp();
const util = require('../../utils/util.js');
var GlobalData = require('../../utils/GlobalData.js');
var dataManager = require('../../utils/dataManager.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    integralData: {},
    integralArr: [],
    nativeShopArr: [],
    /**商品的的种类 */
    goodsKinds: [],
    mallExchange: [],
    localExchange: [],
    localgoods1: { "exchanges": [{ cash: 0, bonuspoints: 0 }], "imgs": "" },
    localgoods2: { "exchanges": [{ cash: 0, bonuspoints: 0 }], "imgs": "" },
    localgoods3: { "exchanges": [{ cash: 0, bonuspoints: 0 }], "imgs": "" },
    shoppingCar: [],
    localgoodsPrice: [{ cash: 0, bonuspoints: 0 }, { cash: 0, bonuspoints: 0 }, { cash: 0, bonuspoints: 0 }],
    picture: "/images/choujiang.png",
    showTabar: true,
    isshowiphonex:false
  },

  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function (options) {
    this.setData({
      showTabar: app.getConfig().isFormal
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (GlobalData.isshowiphone) {
      this.setData({
        isshowiphonex: true
      })
    } else {
      this.setData({
        isshowiphonex: false
      })
    }
    
    // 获取代理信息
    if (GlobalData.homeData && GlobalData.homeData.truename) {
      this.onComplete();
    } else {
      dataManager.rigisterObserver("home", this.onComplete, this)
      dataManager.getHomeData();
    }
    // 积分商城的轮播图

    // if (app.getConfig().isLottery) {
      if (GlobalData.picture.length > 0) {
        this.onSlideComplete();
      } else {
        dataManager.rigisterObserver("getshop_agentBPSlideshow", this.onSlideComplete, this)
        dataManager.getSlideshowData();
      }
    // }


    /**获取商品种类 */
    if (GlobalData.allGoods.length > 0) {
      this.onGetcategoryofgoodsComplete()
    } else {
      dataManager.rigisterObserver("getcategoryofgoods", this.onGetcategoryofgoodsComplete, this)
      dataManager.getCategoryOfGoods();
    }

    /**获取商城兑换数据 */
    /**获取商城兑换商品 */
    // "page", 1, "size", 8,"add","true","exchangeAddress",0, "categoryid",8, 
    if ((JSON.stringify(GlobalData.mallProductList) != '{}') && GlobalData.mallProductList["mall"]) {
      this.onGetMallProductListComplete();
    } else {
      dataManager.rigisterObserver("getLocalList", this.onGetMallProductListComplete, this);
      GlobalData.productType = "mall"
      dataManager.getLocalList();
    }


    /**获取购物车信息 */
    if (GlobalData.shopcarIntegral.length) {
      this.setData({
        shoppingCar: GlobalData.shopcarIntegral
      })
    } else {
      dataManager.rigisterObserver("getshoppingcart", this.onCompleteGetShoppingCar, this);
      dataManager.getShoppingCar();
    }
    /**获取（ 省份 城市 地区） 数据*/
    if (!app.getCitysData()) {
      wx.request({
        url: "https://shopapi.queyouquan.cn/config/list.json",
        header: {
          'content-type': 'application/json'
        },
        method: "GET",
        success: function (res) {
          app.setCitysData(res.data);
          for (var code in app.getCitysData()) {
            if (!(parseInt(code) % 1e4)) {
              let obj = [];
              obj.push(code);
              obj.push(app.getCitysData()[code]);
              GlobalData.CityData.provinceArr.push(obj);
            }
          }
          wx.setStorage({
            key: 'city',
            data: res.data,
          });
        }
      })
    }
  },
  onComplete() {
    this.setData({
      integralData: GlobalData.homeData
    })
  },
  /**获取购物车回调函数 */
  onCompleteGetShoppingCar() {
    // this.shoppingCar = GlobalData.shopcarIntegral;
    this.setData({
      shoppingCar: GlobalData.shopcarIntegral
    })
  },
  // 获取商品种类
  onGetcategoryofgoodsComplete() {
    this.setData({
      goodsKinds: GlobalData.allGoods,
    })
  },
  // 获取商城兑换商品
  onGetMallProductListComplete() {
    let arr = [];
    if (GlobalData.mallProductList["mall"].length > 6) {
      arr = GlobalData.mallProductList["mall"].slice(0, 6)
    } else {
      arr = GlobalData.mallProductList["mall"]
    }
    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr[i].imgs.length; j++) {
        if (arr[i].imgs[j].sortno == 3) {
          arr[i]['img'] = arr[i].imgs[j].path;
        }
      }
    }
    this.setData({
      mallExchange: arr
    })
    // GlobalData.mallProductList
    /**获取本地兑换商品 */
    if ((JSON.stringify(GlobalData.mallProductList) != '{}') && GlobalData.mallProductList["product0"]) {
      this.onEnd();
    } else {
      GlobalData.productType = 0
      dataManager.rigisterObserver("getMallProductList", this.onEnd, this);
      dataManager.getMallProductList(1, 10, false, 0, 0);
    }
  },
  /**回去本地兑换数据 成功的回调函数 */
  onEnd() {
    this.setData({
      localExchange: GlobalData.mallProductList["product0"]
    })
    if (GlobalData.mallProductList["product0"].length) {
      for (let i = 0; i < 3; i++) {
        if (GlobalData.mallProductList["product0"].length == 1) {
          this.data["localgoods" + (i + 1)] = GlobalData.mallProductList["product0"][0];
        } else {
          if (i > GlobalData.mallProductList["product0"].length - 1) {
            this.data["localgoods" + (i + 1)] = GlobalData.mallProductList["product0"][i - GlobalData.mallProductList["product0"].length];
          } else {
            this.data["localgoods" + (i + 1)] = GlobalData.mallProductList["product0"][i];
          }
        }
        if (this.data["localgoods" + (i + 1)] && this.data["localgoods" + (i + 1)].exchanges) {
          for (let k = 0; k < 3; k++) {
            if (this.data["localgoods" + (i + 1)].exchanges.length == 1) {
              this.data.localgoodsPrice[k] = this.data["localgoods" + (i + 1)].exchanges[0]
            } else {
              if (k > (this.data["localgoods" + (i + 1)].exchanges.length - 1)) {
                this.data.localgoodsPrice[k] = this.data["localgoods" + (i + 1)].exchanges[k - this.data["localgoods" + (i + 1)].exchanges.length]
              } else
                this.data.localgoodsPrice[k] = this.data["localgoods" + (i + 1)].exchanges[k]
            }
          }
        }
      }

      for (let j = 0; j < this.data.localgoods1.imgs.length; j++) {
        if (this.data.localgoods1.imgs[j].sortno == 4) {
          this.data.localgoods1['img'] = this.data.localgoods1.imgs[j].path;
        }
        if (this.data.localgoods2.imgs[j].sortno == 3) {
          this.data.localgoods2['img'] = this.data.localgoods2.imgs[j].path;
        }
        if (this.data.localgoods3.imgs[j].sortno == 3) {
          this.data.localgoods3['img'] = this.data.localgoods3.imgs[j].path;
        }
      }

      for (let t = 0; t < this.data.localgoodsPrice.length; t++) {
        if ((parseInt(this.data.localgoodsPrice[t].cash) + parseInt(this.data.localgoodsPrice[t].bonuspoints)) == 0) {
          this.data.localgoodsPrice[t] = this.data.localgoodsPrice[0]
        }
      }
      // /cash: 0, bonuspoints: 0
      this.setData({
        localgoodsPrice: this.data.localgoodsPrice,
        localgoods1: this.data.localgoods1,
        localgoods2: this.data.localgoods2,
        localgoods3: this.data.localgoods3
      })
    }
  },
  onSlideComplete() {
    for (let i = 0; i < GlobalData.picture.length; i++) {
      if (app.getConfig().isFormal) {
        if (GlobalData.picture[i].remark != "1") {
          this.setData({
            picture: GlobalData.picture[i].imgPath
          })
          return;
        }
      } else {
        if (GlobalData.picture[i].remark == "1") {
          this.setData({
            picture: GlobalData.picture[i].imgPath
          })
          return;
        }
      }
    }

  },
  /**前往我的 */
  goMyIntegral: function () {
    dataManager.UseNavigateTo('/pages/myintegral/myintegral', false)

  },
  /**前往商品列表 */
  onProdcutList: function (event) {
    let type = event.currentTarget.dataset.id;
    dataManager.rigisterObserver("getMallProductList", this.onNavigateByUr, this);
    let kindId;
    let exchangeAddress;
    if (parseInt(type)) {
      if (parseInt(type) >= 2) {
        exchangeAddress = 2;
        kindId = type;
      } else {
        exchangeAddress = type;
        kindId = 0;
      }
    } else if (parseInt(type) == 0) {
      exchangeAddress = 0;
      kindId = 0;
    } else {
      exchangeAddress = 2;
      kindId = 0;
    }
    GlobalData.productType = type;
    dataManager.getMallProductList(1, 10, false, exchangeAddress, kindId);

  },
  /**点击相应商品类跳转到商品列表 */
  onNavigateByUr: function () {
    wx.navigateTo({
      url: '/pages/productlist/productlist',
    })
  },
  /**前往购物车 */
  onShoppingCard() {
    dataManager.UseNavigateTo("/pages/shoppingcar/shoppingcar", false)
  },
  /**前往商品详情 */
  onProductDetails(item) {
    // let type = event.currentTarget.dataset.id;
    let id = item.currentTarget.dataset.id.id

    dataManager.rigisterObserver("getgoodsdetails", this.getGoodsDetails, this);
    dataManager.getProductDetails(id);
  },
  /**获取商品详情的回调函数 */
  getGoodsDetails() {
    dataManager.UseNavigateTo("/pages/productdetails/productdetails", false);
  },
  /**抽奖 */
  onLottery() {
    console.log("不抽奖抽奖")
    if (app.getConfig().isFormal && app.getConfig().isLottery) {
      console.log("抽奖")
      dataManager.rigisterObserver("getdrawrecordlist", this.onWinPrizeRecordComplete, this);
      dataManager.getWinRecordDm(1, 1, 10, false);
    }

  },
  onWinPrizeRecordComplete() {
    dataManager.rigisterObserver("getluckydrawprizeconfig", this.getLuckyDrawprizeConfigComplete, this);
    dataManager.getLuckyDrawprizeConfig();

  },
  getLuckyDrawprizeConfigComplete() {
    dataManager.UseNavigateTo("/pages/integralactivities/integralactivities", false);
  },

  goHome: function (event) {
    let index = parseInt(event.currentTarget.dataset.id)
    switch (index) {
      case 2:
      dataManager.UseNavigateTo("/pages/shoppingcar/shoppingcar",true)
        break;
      case 3:
       dataManager.UseNavigateTo("/pages/myintegral/myintegral",true)
        break;
    }
  },
  goHomea: function () {
    dataManager.UseNavigateTo("/pages/component/homes/home/home",true);
  },
  goCardDepots: function () {
    dataManager.UseNavigateTo("/pages/component/carddepots/carddepot/carddepot",true)
    
  },

  /**前往推广 */
  goPromotion: function () {
    if (!GlobalData.homeData.isopendistribution) {
      app.show("该地区暂未开启推广功能");
      return;
    }
    else if (GlobalData.homeData.isopendistribution && (GlobalData.homeData.isdefaultlevels && !GlobalData.homeData.isdefaultshare)) {
      // this.showTxt("提示", "添加商务微信" + GlobalData.homeData.businessname + "，即可开通推广功能", "确认复制微信号");
      this.showTxt();
      return;
    }
    else {
      this.setData({
        hidden: false
      })
      dataManager.UseNavigateTo("/pages/component/promotions/promotion/promotion",true)
    }
  },
  showTxt: function (e) {
    var str = ""
    if (GlobalData.homeData.businessname)
      str = GlobalData.homeData.businessname
    var msg = "添加商务微信" + GlobalData.homeData.businessname + "，即可开通推广功能"
    wx.showModal({
      title: "提示",
      content: msg,
      showCancel: true,
      confirmText: "确认复制",
      success: function (res) {
        if (res.confirm) {
          wx.setClipboardData({
            data: str,
            success() {
              wx.getClipboardData({
                success(res) {
                  // app.show("已复制成功。")
                }
              })
            },
            fail(res) {
              console.error(res)
            }
          })
        }
      }
    })
  },
})